#!/bin/bash
# 用户迁移脚本 - 保持UID/GID一致

# 检查是否为root用户
if [ "$(id -u)" -ne 0 ]; then
    echo "错误：必须使用root权限运行此脚本！" >&2
    exit 1
fi

# 定义输出文件
USER_FILE="/tmp/user_migration.sh"
GROUP_FILE="/tmp/group_migration.sh"

# 清空旧文件
> "$USER_FILE"
> "$GROUP_FILE"

# 添加脚本头
echo "#!/bin/bash" >> "$USER_FILE"
echo "# 自动生成的用户创建脚本" >> "$USER_FILE"
echo "# 请在目标系统以root身份执行" >> "$USER_FILE"
echo "" >> "$USER_FILE"

echo "#!/bin/bash" >> "$GROUP_FILE"
echo "# 自动生成的组创建脚本" >> "$GROUP_FILE"
echo "# 请在目标系统以root身份执行" >> "$GROUP_FILE"
echo "" >> "$GROUP_FILE"

# 生成用户创建命令
echo "echo '开始创建用户...'" >> "$USER_FILE"
echo "echo '开始创建组...'" >> "$GROUP_FILE"

# 处理所有smb-开头的用户
getent passwd | grep -E '^smb-' | while IFS=: read -r username password uid gid gecos home shell; do
    # 创建用户命令
    echo "if ! getent passwd '$username' >/dev/null; then" >> "$USER_FILE"
    echo "    echo '创建用户: $username (UID:$uid GID:$gid)'" >> "$USER_FILE"
    echo "    groupadd -g $gid '$username' 2>/dev/null || true" >> "$USER_FILE"
    echo "    useradd -u $uid -g $gid -c '$gecos' -d '$home' -s '$shell' '$username'" >> "$USER_FILE"
    echo "else" >> "$USER_FILE"
    echo "    echo '用户已存在: $username'" >> "$USER_FILE"
    echo "fi" >> "$USER_FILE"
    echo "" >> "$USER_FILE"
done

# 处理所有samba-开头的组
getent group | grep -E '^samba-' | while IFS=: read -r groupname password gid members; do
    # 创建组命令
    echo "if ! getent group '$groupname' >/dev/null; then" >> "$GROUP_FILE"
    echo "    echo '创建组: $groupname (GID:$gid)'" >> "$GROUP_FILE"
    echo "    groupadd -g $gid '$groupname'" >> "$GROUP_FILE"
    echo "else" >> "$GROUP_FILE"
    echo "    echo '组已存在: $groupname'" >> "$GROUP_FILE"
    echo "fi" >> "$GROUP_FILE"
    
    # 添加组成员
    if [ -n "$members" ]; then
        echo "echo '设置组成员: $groupname -> $members'" >> "$GROUP_FILE"
        IFS=',' read -ra MEMBER_ARRAY <<< "$members"
        for member in "${MEMBER_ARRAY[@]}"; do
            echo "usermod -a -G '$groupname' '$member' 2>/dev/null || echo '无法添加用户 $member 到组 $groupname'" >> "$GROUP_FILE"
        done
    fi
    echo "" >> "$GROUP_FILE"
done

# 添加执行权限
chmod +x "$USER_FILE" "$GROUP_FILE"

echo "迁移脚本已生成:"
echo "- 用户创建脚本: $USER_FILE"
echo "- 组创建脚本: $GROUP_FILE"
echo ""
echo "请将这些文件复制到目标系统并执行:"
echo "1. 先执行组脚本: sudo bash $GROUP_FILE"
echo "2. 再执行用户脚本: sudo bash $USER_FILE"
